package com.dh.blog.service.impl;

import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dh.blog.dao.SysFileDao;
import com.dh.blog.handler.SaveFileHandler;
import com.dh.blog.service.FileService;
import com.dh.blog.vo.MATFileVo;
import com.dh.blog.vo.SimpleFileVo;
import com.ewei.web.common.exception.MessageRuntimeException;
import com.mysql.jdbc.StringUtils;

@Service("fileService")
@Transactional(readOnly=true)
public class FileServiceImpl implements FileService {
	private static final Logger logger = LogManager.getLogger(FileServiceImpl.class);
	@Resource
	private SysFileDao sysFileDao;
	@Resource
	private SaveFileHandler saveFile;
	@Resource
	private Properties config;
	@Override
	@Transactional(readOnly=false)
	public void doCheck() {
		String params = config.getProperty("file_max_exits");
		if(!StringUtils.isNullOrEmpty(params)){
			int maxExitTime = Integer.valueOf(params); 
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.HOUR_OF_DAY,-maxExitTime);
			List<SimpleFileVo> list = sysFileDao.check(calendar.getTime());
			if(!list.isEmpty()){
				for(SimpleFileVo file : list){
					logger.info("deleting uploaded file.... path is "+file.getPath());
					saveFile.remove(file.getPath());
				}
			}
		}
	}

	@Override
	@Transactional(readOnly=false)
	public void doSaveSysFile(SimpleFileVo file) {
		sysFileDao.addSimpleOne(file);
	}

	@Override
	public List<MATFileVo> getMATFileList(String userId) {
		return sysFileDao.getMATFiles(userId);
	}

	@Override
	public MATFileVo getMATFile(String id) {
		return sysFileDao.getMATFile(id);
	}
	@Override
	@Transactional(readOnly=false)
	public void doSaveMATFile(MATFileVo file) {
		sysFileDao.addMATOne(file);
	}

	@Override
	@Transactional(readOnly=false)
	public void deleteMATFiles(List<MATFileVo> vos) {
		MATFileVo[] files = new MATFileVo[vos.size()];
		vos.toArray(files);
		String[] ids = new String[vos.size()];
		for(int i = 0;i<files.length;i++){
			MATFileVo file = files[i];
			try{
				saveFile.remove(file.getPath());
			}catch(Exception ex){
				throw new MessageRuntimeException(ex);
			}
			ids[i] = file.getPath();
		}
		sysFileDao.deleteMany(ids);
	}

}
